package com.tlgen.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tlgen.model.RespBean;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: tlgen
 * @Discription: 把验证码校验放在UsernamePasswordAuthentication前边 在security中自定义过滤链
 */
@Component
public class VerificationCodeFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if ("POST".equals(request.getMethod()) && "/doLogin".equals(request.getServletPath())) {
            //登录请求
            String code = request.getParameter("code"); //用户输入的验证码文字
            String verify_code = (String) request.getSession().getAttribute("verify_code"); //从session拿到生成的验证码 把Object强转成String
            //校验验证码
            if (code == null || "".equals(code) || !verify_code.equals(code)) {
                //验证码不正确
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(RespBean.error("验证码填写错误!")));
                out.flush();
                out.close();
                return;
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            //不是登录请求 直接过
            filterChain.doFilter(request, response);
        }
    }
}
